#include "stdafx.h"

#include <algorithm>

#include "Language.h"

bool CLanguage::ParseGlobals(CString fileName)
{
	bool rtn = true;
	CString line = _T("");
	int lineNum = 0;

	for(list<CString>::iterator itr = m_Lines[fileName].begin();
			itr != m_Lines[fileName].end(); itr++)
	{
		line.Format(_T("%s"),*itr);
		lineNum++;

		// globals will not be inside of function
		// ignore function lines
		if(InsideFunction(line) || line.Find('(') != -1
			|| line.Find('#') != -1)
			continue;

		// if we are here, the line contains something that is not
		// a function or in a function and is not a comment
		if(line.Find(_T(KEYWORD_GLOBAL)) != -1 &&
			line.Find(' ') == line.ReverseFind(' ') &&
			line.Find(' ') != 0)
		{
			// check for type keyword
			// get variable name
			// check program's add global return value
			// if it returns false, then the global is already defined
			rtn = ParseGlobalLine(line);
		}
		else
		{
		// error
			// no global keyword
			rtn = false;
		}
	}

	return rtn;
}

bool CLanguage::ParseGlobalLine(CString line)
{
	bool rtn = true;

	list<CString> tokens = SplitString(line);

	if(tokens.size() != 3)
	{
		// error, find out what
		rtn = false;
	}
	else
	{
		if(*tokens.begin() != _T(KEYWORD_GLOBAL))
		{
			// statement in global space, but not a function or global variable
			rtn = false;
		}
		else if(find(m_Types.begin(), m_Types.end(), *(tokens.begin()++)) == m_Types.end())
		{
			// statement doesn't have valid type descriptor
			rtn = false;
		}
		else
		{
			CVariable *var;
			if(*(tokens.begin()++) == "int")
				var = new CInt();
			else if(*(tokens.begin()++) == "string")
				var = new CMyString();
			rtn = m_Program.AddGlobal(*((tokens.begin()++)++), var);
		}
	}

	return rtn;
}